package userProcess

import (
	"../../common/socket"
	"../../common/utils"
	"encoding/json"
	"errors"
	"fmt"
	"net"
)


type UserProcess struct {

	id string
	pass string
	conn net.Conn
}

//连接操作
func (this *UserProcess) Conn(){
	conn,err:=net.Dial("tcp","101.200.150.2:8082")
	utils.HanddleError(err,"客户端拨号出错")
	this.conn=conn
}

//发送登录数据
func (this *UserProcess) Login() (error){
	fmt.Println("请输入账号")
	var id string
	fmt.Scanln(&id)
	fmt.Println("请输入密码")
	var password string
	fmt.Scanln(&password)
	this.Conn()
	defer this.conn.Close()
	conn:=this.conn
	userLogin:=socket.UserLogin{
		Id:   id,
		Pass: password,
	}
	userLogin_byte,err:=json.Marshal(userLogin)
	utils.HanddleError(err,"登录序列化失败")
	data:=socket.Data{
		DataType: socket.LoginType,
		Message:  string(userLogin_byte),
	}
	data_byte,err:=json.Marshal(data)
	utils.HanddleError(err,"数据序列化失败")
	_,err=conn.Write(data_byte)
	 var statusData=new(socket.Data)
	var status=new(socket.Status)
	var byte_slice []byte
	for  {
		_,read_slice,n,err:=socket.Read(this.conn)
		err=json.Unmarshal(read_slice[:n],statusData)
		utils.HanddleError(err,"客户端读取数据序列化失败")
		byte_slice=[]byte(statusData.Message)
		err=json.Unmarshal(byte_slice,status)
		utils.HanddleError(err,"客户端序列化状态失败")
		if status.Code!="200" {
			return errors.New("invalid account,账号密码错误,请重新输入")
		}else{
			break
		}
	}

	if status.OnlineUser==nil{
		fmt.Println("当前暂时没有用户在线")
	}else {
		fmt.Println("当前在线用户如下")
		for _,id:=range status.OnlineUser{
			fmt.Println("用户:",id,"在线中")
		}
	}
	//挂起协程,随时监听用户上下线信息
	go keepReceive(conn)
	//显示登录成功的菜单
	loginSuccessMenu(conn,id)

	return nil
}

func (this *UserProcess) Register() (error){
	fmt.Println("请输入账号")
	var id string
	fmt.Scanln(&id)
	fmt.Println("请输入密码")
	var password string
	fmt.Scanln(&password)
	this.Conn()
	defer this.conn.Close()
	conn:=this.conn
	user:=socket.UserRegister{
		Id:   id,
		Pass: password,
	}
	user_byte,err:=json.Marshal(user)
	utils.HanddleError(err,"注册序列化失败")
	data:=socket.Data{
		DataType: socket.RegisterType,
		Message:  string(user_byte),
	}
	data_byte,err:=json.Marshal(data)
	utils.HanddleError(err,"注册数据序列化失败")
	_,err=conn.Write(data_byte)
	var statusData=new(socket.Data)
	var status=new(socket.Status)
	var byte_slice []byte
	for   {
		_,read_slice,n,err:=socket.Read(this.conn)
		err=json.Unmarshal(read_slice[:n],statusData)
		utils.HanddleError(err,"客户端读取数据序列化失败")
		byte_slice=[]byte(statusData.Message)
		err=json.Unmarshal(byte_slice,status)
		utils.HanddleError(err,"客户端序列化状态失败")
		if status.Code!="200" {
			return errors.New("注册失败,该账号被注册了")
		}else{

			break
		}
	}
	return nil
}



